<template>
    <div class="map-page">
        <div id="map" class="map-container"></div>

        <MapToolbar title="绘制工具" :show-draw-buttons="true" :draw-buttons="drawButtons" @remove="removeEntity"
            @removeAll="removeAllEntities" @hideAll="hideAllEntities" @showAll="showAllEntities"
            @toggleEdit="toggleEdit" />
    </div>
</template>
<script setup>
import { onMounted, reactive, ref, computed } from 'vue'
import Map from '289-map'
import Mock from 'mockjs'
import MapToolbar from '@/components/MapToolbar.vue'
import {
    Edit,
    Location,
    Aim,
    Monitor,
    Document,
    CircleCheck,
    Connection,
    Switch
} from '@element-plus/icons-vue'

const TDT_KEY = '598b1d1a4ed6d42ce765e7b6c3737c6b'
const basemaps = [
  {
    id: 'tdt-vector',
    label: '天地图矢量',
    thumb: 'https://t0.tianditu.gov.cn/DataServer?T=vec_w&x=0&y=0&l=2&tk=598b1d1a4ed6d42ce765e7b6c3737c6b',
    baseTiles: ['https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=598b1d1a4ed6d42ce765e7b6c3737c6b'],
    labelTiles: ['https://t0.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=598b1d1a4ed6d42ce765e7b6c3737c6b']
  },
  {
    id: 'tdt-image',
    label: '天地图影像',
    thumb: 'https://t0.tianditu.gov.cn/DataServer?T=img_w&x=0&y=0&l=2&tk=598b1d1a4ed6d42ce765e7b6c3737c6b',
    baseTiles: ['https://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=598b1d1a4ed6d42ce765e7b6c3737c6b'],
    labelTiles: ['https://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=598b1d1a4ed6d42ce765e7b6c3737c6b']
  },
  {
    id: 'tdt-terrain',
    label: '天地图地形',
    thumb: 'https://t0.tianditu.gov.cn/DataServer?T=ter_w&x=0&y=0&l=2&tk=598b1d1a4ed6d42ce765e7b6c3737c6b',
    baseTiles: ['https://t0.tianditu.gov.cn/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=598b1d1a4ed6d42ce765e7b6c3737c6b'],
    labelTiles: ['https://t0.tianditu.gov.cn/DataServer?T=cta_w&x={x}&y={y}&l={z}&tk=598b1d1a4ed6d42ce765e7b6c3737c6b']
  },
]

const entities = reactive([])
let map = ref(null);
function toggleEdit() {
    for (const item of entities) {
        item.edit = !item.edit
    }
}

function addTdtSourceAndLayer(map, item, visible) {
  const baseType = item.id === 'tdt-vector' ? 'vec_w' : item.id === 'tdt-image' ? 'img_w' : 'ter_w';
  const labelType = item.id === 'tdt-vector' ? 'cva_w' : item.id === 'tdt-image' ? 'cia_w' : 'cta_w';
  const baseTiles = [`https://t0.tianditu.gov.cn/DataServer?T=${baseType}&x={x}&y={y}&l={z}&tk=${TDT_KEY}`];
  const labelTiles = [`https://t0.tianditu.gov.cn/DataServer?T=${labelType}&x={x}&y={y}&l={z}&tk=${TDT_KEY}`];

  // 主底图 source/layer
  if (!map.getSource(item.id)) {
    map.addSource(item.id, {
      type: 'raster',
      tiles: baseTiles,
      tileSize: 256,
      attribution: '© 天地图'
    });
  }
  if (!map.getLayer(item.id + '-layer')) {
    map.addLayer({
      id: item.id + '-layer',
      type: 'raster',
      source: item.id,
      layout: { visibility: visible ? 'visible' : 'none' }
    }, map.getStyle().layers?.[0]?.id);
  }

  // 标注 source/layer
  if (!map.getSource(item.id + '-label')) {
    map.addSource(item.id + '-label', {
      type: 'raster',
      tiles: labelTiles,
      tileSize: 256,
      attribution: '© 天地图'
    });
  }
  if (!map.getLayer(item.id + '-label-layer')) {
    map.addLayer({
      id: item.id + '-label-layer',
      type: 'raster',
      source: item.id + '-label',
      layout: { visibility: visible ? 'visible' : 'none' }
    });
  }
}

onMounted(async () => {
    map.value = new Map('map', {
        style: {
          version: 8,
          sources: {},
          layers: [],
        },
        center: {
            lng: 116.40,
            lat: 39.90,
            heading: 0,
            pitch: 0
        },
        zoom: 5,
        controller: ["global", "showZoom", "showCompass", "fullscreen", "basemapSwitcher"],
        basemaps,
        type: 'mercator',
        overview: true,
        contextMenuItems: [
            {
                id: 'custom-menu-onmount',
                label: '自定义1',
                onClick: (lngLat, mapInstance, ev) => {
                    alert(`自定义1`)
                }
            },
            {
                id: 'custom-menu-demo',
                label: '自定义2',
                onClick: (lngLat, mapInstance, ev) => {
                    alert(`自定义2`)
                }
            },
            {
                id: 'custom-menu-demo3',
                label: '自定义3',
                onClick: (lngLat, mapInstance, ev) => {
                    alert(`自定义3`)
                }
            },
        ]
    })
    map.value.on('load', () => {
      basemaps.forEach((item, idx) => {
        addTdtSourceAndLayer(map.value, item, idx === 0)
      })
    })
})

const drawButtons = computed(() => [
    {
        label: '复合图形',
        type: 'primary',
        icon: Connection,
        onClick: () => draw('CompositeBillboardLineLabel')
    },
    {
        label: '标签',
        type: 'primary',
        icon: Document,
        onClick: () => draw('Label')
    },
    {
        label: '标记点',
        type: 'primary',
        icon: Location,
        onClick: () => draw('BillboardEntity')
    },
    {
        label: '点',
        type: 'default',
        icon: CircleCheck,
        onClick: () => draw('Point')
    },
    {
        label: '线',
        type: 'default',
        icon: Edit,
        onClick: () => draw('Line')
    },
    {
        label: '面',
        type: 'default',
        icon: Monitor,
        onClick: () => draw('Polygon')
    },
    {
        label: '矩形',
        type: 'default',
        icon: Monitor,
        onClick: () => draw('Rectangle')
    },
    {
        label: '直箭头',
        type: 'default',
        icon: Aim,
        onClick: () => draw('StraightArrow')
    },
    {
        label: '攻击箭头',
        type: 'default',
        icon: Aim,
        onClick: () => draw('AttackArrow')
    },
    {
        label: '钳击箭头',
        type: 'default',
        icon: Aim,
        onClick: () => draw('DoubleArrow')
    },
    {
        label: '燕尾粗直箭头',
        type: 'default',
        icon: Aim,
        onClick: () => draw('SwallowtailArrow')
    },
    {
        label: '底部曲线箭头',
        type: 'default',
        icon: Aim,
        onClick: () => draw('BottomCurveArrow')
    },
    {
        label: '集结地',
        type: 'primary',
        icon: Monitor,
        onClick: () => draw('GatheringPlace')
    }
])

const draw = async (type) => {
    let graphic;
    if (type === 'CompositeBillboardLineLabel') {
        graphic = map.value.startDraw({
            type: 'CompositeBillboardLineLabel',
            billboard: {
                style: {
                    image: await import('@/assets/images.jpg'),
                    width: 64,
                    height: 64,
                },
                drag: true
            },
            label: {
                style: {
                    text: '自定义标记',
                    font_size: 16,
                    font_weight: 'bold',
                    color: 'green',
                },
                drag: true
            },
            line: {
                style: {
                    width: 2,
                    color: '#ff0000',
                    opacity: 0.7 // 线的透明度
                }
            },
            onDrawEnd: (entity) => {
                if (entity) entities.push(entity);
            },
        })
    }

    if (type === 'Label') {
        graphic = map.value.startDraw({
            type: 'Label',
            style: {
                text: '自定义标记',
                font_size: 16,
                font_weight: 'bold',
                color: 'green',
            },
            popup: '<div>这是一个Label</div>',
            popupTrigger: 'click', // 点击触发弹窗
            popupOptions: {
                closeButton: true, // 显示关闭按钮
                maxWidth: '200px', // 弹窗最大宽度
            },
            onDrawEnd: (entity) => {
                if (entity) entities.push(entity);
            },
            drag: true
        })
    }
    if (type === 'BillboardEntity') {
        graphic = map.value.startDraw({
            type: 'BillboardEntity',
            style: {
                image: await import('@/assets/images.jpg'),
                width: 64,
                height: 64,
                label: {
                    text: '自定义标记',
                    font_size: 16,
                    font_weight: 'bold',
                    color: 'green',
                    pixelOffsetY: 90, // 调整标签位置
                    pixelOffsetX: 30, // 水平偏移
                }
            },
            popup: '<div>这是一个自定义标记</div>',
            popupTrigger: 'click', // 点击触发弹窗
            popupOptions: {
                closeButton: true, // 显示关闭按钮
                maxWidth: '200px', // 弹窗最大宽度
            },
            onDrawEnd: (entity) => {
                if (entity) entities.push(entity);
            },
            drag: true
        })
    }
    if (type === 'Point') {
        map.value.startDraw({
            type: 'Point',
            style: {
                width: 100,
                color: '#ff0000',
                opacity: 0.5
            },
            popup: '这是个点',
            popupTrigger: 'mouse', // 点击触发弹窗
            popupOptions: {
                closeButton: true, // 显示关闭按钮
                maxWidth: '200px', // 弹窗最大宽度
            },
            onDrawEnd: (entity) => {
                if (entity) entities.push(entity);
            },
            drag: true
        })
    }
    if (type === 'Line') {
        graphic = map.value.startDraw({
            type: 'Line',
            style: {
                width: 6,
                color: '#ff0000',
                opacity: 0.7, // 线的透明度
            },
            edit: true, // 支持编辑
            popup: '这是个线',
            popupTrigger: 'click', // 点击触发弹窗
            popupOptions: {
                closeButton: true, // 显示关闭按钮
                maxWidth: '200px', // 弹窗最大宽度
            },
            onDrawEnd: (entity) => {
                if (entity) entities.push(entity);
            },
            drag: true
        })
    }
    if (type === 'Polygon') {
        graphic = map.value.startDraw({
            type: 'Polygon',
            style: {
                color: '#ff0000',
                opacity: 0.5,
                outlineColor: '#000000',
                outlineWidth: 2,
            },
            edit: true, // 支持编辑
            popup: '这是个面',
            popupTrigger: 'click', // 点击触发弹窗
            popupOptions: {
                closeButton: true, // 显示关闭按钮
                maxWidth: '200px', // 弹窗最大宽度
            },
            onDrawEnd: (entity) => {
                if (entity) entities.push(entity);
            },
            drag: true
        })
    }
    if (type === 'Rectangle') {
        graphic = map.value.startDraw({
            type: 'Rectangle',
            style: {
                color: '#ff8800',
                opacity: 0.5,
                borderColor: '#0088ff', // 新增边框颜色
                borderWidth: 4,        // 新增边框宽度
                borderOpacity: 0.9,    // 新增边框透明度
                outlineColor: '#000000', // 兼容outline参数
                outlineWidth: 2,
            },
            edit: true, // 支持编辑
            popup: '这是个矩形',
            popupTrigger: 'click', // 点击触发弹窗
            popupOptions: {
                closeButton: true, // 显示关闭按钮
                maxWidth: '200px', // 弹窗最大宽度
            },
            onDrawEnd: (entity) => {
                if (entity) entities.push(entity);
            },
            drag: true
        })
    }
    if (type === "StraightArrow") {
        graphic = map.value.startDraw({
            type: 'StraightArrow',
            style: {
                color: '#ff0000', // 箭头颜色
                // width: 20, // 箭头线宽
                opacity: 0.8, // 箭头透明度
                outline: true, // 是否显示轮廓
                outlineColor: '#fff', // 轮廓颜色
                outlineWidth: 3, // 轮廓宽度
            },
            edit: true, // 支持编辑
            popup: '粗直箭头: 支持传入起点和终点坐标',
            popupTrigger: 'click', // 点击触发弹窗
            popupOptions: {
                closeButton: true, // 显示关闭按钮
                maxWidth: '200px', // 弹窗最大宽度
            },
            onDrawEnd: (entity) => {
                if (entity) entities.push(entity);
            },
            drag: true
        })
    }
    if (type === "AttackArrow") {
        graphic = map.value.startDraw({
            type: 'AttackArrow',
            style: {
                color: '#ff0000', // 箭头颜色
                width: 20, // 箭头线宽
                opacity: 0.8, // 箭头透明度
                outline: true, // 是否显示轮廓
                outlineColor: '#fff', // 轮廓颜色
                outlineWidth: 3, // 轮廓宽度
            },
            edit: true, // 支持编辑
            popup: '攻击箭头：支持传入多个坐标点',
            popupTrigger: 'click', // 点击触发弹窗
            popupOptions: {
                closeButton: true, // 显示关闭按钮
                maxWidth: '200px', // 弹窗最大宽度
            },
            onDrawEnd: (entity) => {
                if (entity) entities.push(entity);
            },
            drag: true
        })
    }
    if (type === "DoubleArrow") {
        graphic = map.value.startDraw({
            type: 'DoubleArrow',
            style: {
                color: '#ff6600', // 钳击箭头颜色
                width: 20, // 箭头线宽
                opacity: 0.8, // 箭头透明度
                outline: true, // 是否显示轮廓
                outlineColor: '#fff', // 轮廓颜色
                outlineWidth: 3, // 轮廓宽度
            },
            edit: true, // 支持编辑
            popup: '钳击箭头：支持4个坐标点，形成双向箭头',
            popupTrigger: 'click', // 点击触发弹窗
            popupOptions: {
                closeButton: true, // 显示关闭按钮
                maxWidth: '200px', // 弹窗最大宽度
            },
            onDrawEnd: (entity) => {
                if (entity) entities.push(entity);
            },
            drag: true
        })
    }
    if (type === "SwallowtailArrow") {
        graphic = map.value.startDraw({
            type: 'SwallowtailArrow',
            style: {
                color: '#1e90ff', // 燕尾箭头颜色
                // width: 20, // 箭头线宽
                opacity: 0.8, // 箭头透明度
                outline: true, // 是否显示轮廓
                outlineColor: '#fff', // 轮廓颜色
                outlineWidth: 3, // 轮廓宽度
            },
            edit: true, // 支持编辑
            popup: '燕尾粗直箭头: 支持传入起点和终点坐标，尾部为燕尾',
            popupTrigger: 'click', // 点击触发弹窗
            popupOptions: {
                closeButton: true, // 显示关闭按钮
                maxWidth: '200px', // 弹窗最大宽度
            },
            onDrawEnd: (entity) => {
                if (entity) entities.push(entity);
            },
            drag: true
        })
    }
    if (type === "BottomCurveArrow") {
        graphic = map.value.startDraw({
            type: 'BottomCurveArrow',
            style: {
                color: '#00bfff', // 箭头颜色
                // width: 20, // 箭头线宽
                opacity: 0.8, // 箭头透明度
                outline: true, // 是否显示轮廓
                outlineColor: '#fff', // 轮廓颜色
                outlineWidth: 3, // 轮廓宽度
            },
            edit: true, // 支持编辑
            popup: '底部曲线箭头: 支持传入起点和终点坐标',
            popupTrigger: 'click', // 点击触发弹窗
            popupOptions: {
                closeButton: true, // 显示关闭按钮
                maxWidth: '200px', // 弹窗最大宽度
            },
            onDrawEnd: (entity) => {
                if (entity) entities.push(entity);
            },
            drag: true
        })
    }
    if (type === 'GatheringPlace') {
        graphic = map.value.startDraw({
            type: 'GatheringPlace',
            style: {
                color: '#FFD700', // 金色
                opacity: 0.5,
                outlineColor: '#000',
                outlineWidth: 2,
            },
            edit: true, // 支持编辑
            popup: '这是一个集结地',
            popupTrigger: 'click',
            popupOptions: {
                closeButton: true,
                maxWidth: '200px',
            },
            onDrawEnd: (entity) => {
                if (entity) entities.push(entity);
            },
            drag: true
        })
    }
}

const removeEntity = () => {
    for (const item of entities) {
        map.value.removeGraphic(item);
    }
}

const removeAllEntities = () => {
    entities.length = 0; // 清空实体数组
    map.value.removeAllGraphics(); // 清除地图上的所有图形
}
const hideAllEntities = () => {
    for (const item of entities) {
        item.show = false;
    }
}
const showAllEntities = () => {
    for (const item of entities) {
        item.show = true;
    }
}

</script>

<style lang="scss" scoped>
.map-page {
    position: relative;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
}

.map-container {
    width: 100%;
    height: 100%;
}

.page-info {
    position: absolute;
    top: 20px;
    right: 20px;
    z-index: 1000;
    max-width: 320px;
}

.info-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);

    h3 {
        margin: 0 0 12px 0;
        color: #2c3e50;
        font-size: 16px;
        font-weight: 600;
    }

    p {
        margin: 0 0 16px 0;
        color: #7f8c8d;
        font-size: 14px;
        line-height: 1.5;
    }
}

.feature-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.feature-item {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
    color: #5a6c7d;

    .feature-icon {
        font-size: 16px;
    }
}

// 响应式设计
@media (max-width: 768px) {
    .page-info {
        top: 10px;
        right: 10px;
        left: 10px;
        max-width: none;
    }

    .info-card {
        padding: 16px;
    }

    .info-card h3 {
        font-size: 15px;
    }

    .info-card p {
        font-size: 13px;
    }

    .feature-item {
        font-size: 12px;
    }
}
</style>